﻿using AMS.Services.DomainModels;
using Newtonsoft.Json;
using OA.Infrastructure.Abstractions;

namespace AMS.WebApi.Controllers;

[ApiController]
public class PermissionTemporaryAuthorizationController : ControllerBase
{
    private readonly ITemporaryAuthorizationService<TemporaryAuthorizationPermissionModel> _service;

    public PermissionTemporaryAuthorizationController(ITemporaryAuthorizationService<TemporaryAuthorizationPermissionModel> service)
    {
        _service = service;
    }

    // POST api/permission-temp-auth/acquire
    [HttpPost("api/permission-temp-auth/acquire")]
    public async Task<string> TryAcquireAsync()
    {
        using var reader = new StreamReader(Request.Body);

        var model = JsonConvert.DeserializeObject<TemporaryAuthorizationPermissionModel>(await reader.ReadToEndAsync());

        return await _service.TryAcquireAsync(model, HttpContext.RequestAborted);
    }

    // GET api/permission-temp-auth/grant
    [HttpGet("api/permission-temp-auth/grant")]
    public async Task GrantAsync([FromQuery] string key)
    {
        await _service.GrantAsync(key, HttpContext.RequestAborted);
    }

    // GET api/permission-temp-auth/reject
    [HttpGet("api/permission-temp-auth/reject")]
    public async Task RejectAsync([FromQuery] string key)
    {
        await _service.RejectAsync(key, HttpContext.RequestAborted);
    }
}